﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using WebPages.Bll;

namespace WebPages.Account
{
    public partial class UserProfile : System.Web.UI.Page
    {
        ProfileBase profile;

        CloudBlobClient blobClient = null;
        CloudBlobContainer blobContainer = null;

        void ShowControls(bool isCurrentUser)
        {
            PrivateGender.Visible = isCurrentUser;
            PublicGender.Visible = !isCurrentUser;
            UploadPortrait.Visible = isCurrentUser;
            SubmitButton.Visible = isCurrentUser;
        }

        ProfileBase GetProfile(out bool isCurrentUser)
        {
            var requestedUserName = Request.Params["name"];
            var currentUser = Membership.GetUser();

            ProfileBase foundProfile = null;
            
            if (currentUser != null && (requestedUserName == currentUser.UserName || String.IsNullOrEmpty(requestedUserName) ))
            {
                foundProfile = HttpContext.Current.Profile;
                isCurrentUser = true;
            }
            else
            {
                isCurrentUser = false;

                if (String.IsNullOrEmpty(requestedUserName))
                {
                    // Nothing to do since no user was specified
                    FormsAuthentication.RedirectToLoginPage();
                    return foundProfile; ;
                }

                foundProfile = ProfileBase.Create(requestedUserName, true);
            }

            if (foundProfile == null)
            {
                // Profile was not found
                FormsAuthentication.RedirectToLoginPage();
            }

            return foundProfile;
        }

        string GetGender()
        {
            string gender;
            switch ((int)profile.GetPropertyValue("Gender"))
            {
                case -1:
                    gender = Resources.Profile.NotSet;
                    break;
                case 0:
                    gender = Resources.Profile.GenderFemale;
                    break;
                case 1:
                    gender = Resources.Profile.GenderMale;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(Resources.Profile.UnknownGenderError);
            }
            return gender;
        }

        void PopulateGenderDropDown()
        {
            var genderVal = (int)profile.GetPropertyValue("Gender");
            PrivateGender.Items.Add(
                new ListItem(Resources.Profile.NotSet, "-1") { Selected = (genderVal == -1) }
                );
            PrivateGender.Items.Add(
                new ListItem(Resources.Profile.GenderFemale, "0") { Selected = (genderVal == 0) }
                );
            PrivateGender.Items.Add(
                new ListItem(Resources.Profile.GenderMale, "1") { Selected = (genderVal == 1) }
                );
        }

        void GetPortrait()
        {
            var blobAddressUri = (string)profile.GetPropertyValue("PortraitBlobAddressUri");

            if (String.IsNullOrEmpty(blobAddressUri)) return;

            var blob = blobContainer.GetBlobReference(blobAddressUri);
            PortraitImage.ImageUrl = blob.Uri.ToString();
            PortraitImage.AlternateText = blob.Metadata["Description"];
        }

        void InitControls(bool isCurrentUser)
        {
            ShowControls(isCurrentUser);

            TitleUserName.Text = UserName.Text = profile.UserName;

            if (isCurrentUser)
            {
                PopulateGenderDropDown();
            }
            else
            {
                PublicGender.Text = GetGender();
            }

            GetPortrait();
        }

        void SetBlobPermissions()
        {
            // Setup the permissions on the container to be public
            var permissions = new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Container
            };

            blobContainer.SetPermissions(permissions);
        }

        void InitBlob()
        {
            // Setup the connection to Windows Azure Storage
            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            blobClient = storageAccount.CreateCloudBlobClient();

            // Get and create the container
            blobContainer = blobClient.GetContainerReference("publicfiles");
            if (blobContainer.CreateIfNotExist()) SetBlobPermissions();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            InitBlob();

            bool isCurrentUser;

            profile = GetProfile(out isCurrentUser);
            if (profile == null) return;

            if (!IsPostBack) InitControls(isCurrentUser);
        }

        protected void SubmitButton_Click(Object sender, EventArgs eventArgs)
        {
            var genderVal = Int32.Parse(PrivateGender.SelectedValue);
            profile.SetPropertyValue("Gender", genderVal);
        }

        protected void PortraitSubmitButton_Click(object sender, EventArgs e)
        {
            if (profile == null || String.IsNullOrEmpty(PortraitUploadControl.FileName)) return;

            var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
            blobClient = storageAccount.CreateCloudBlobClient();

            // Make a unique blob name
            var extension = System.IO.Path.GetExtension(PortraitUploadControl.FileName);

            // Create the Blob and upload the file
            var blobAddressUri = String.Format( "{0}{1}" , Guid.NewGuid(), extension);
            var blob = blobContainer.GetBlobReference(blobAddressUri);

            var graphics = new GraphicUtilities();
            blob.UploadFromStream(graphics.CreateThumbnail(PortraitUploadControl.FileContent));

            // Update the profile with the new blob address Uri
            profile.SetPropertyValue("PortraitBlobAddressUri", blobAddressUri);

            // Set the metadata into the blob
            var userName = Membership.GetUser().UserName;
            blob.Metadata["FileName"] = PortraitUploadControl.FileName;
            blob.Metadata["Submitter"] = userName;
            blob.Metadata["Type"] = "Portrait";
            blob.Metadata["Width"] = "64px";
            blob.Metadata["Height"] = "64px";
            blob.Metadata["Description"] = String.Format("Portrait of {0}", userName);
            blob.SetMetadata();

            // Set the properties
            blob.Properties.ContentType = PortraitUploadControl.PostedFile.ContentType;
            blob.SetProperties();

            // Show the portrait
            GetPortrait();
        }
    }
}